Include Ensemble

/// HealthConnect消息及服务的一些统计示例<br/>
/// Business logic class defined by OpenAPI in HCC.Interface.Monitor.spec<br/>
/// Updated May 11, 2023 02:53:27
Class HCC.Interface.Monitor.impl Extends %REST.Impl [ ProcedureBlock ]
{

/// If ExposeServerExceptions is true, then details of internal errors will be exposed.
Parameter ExposeServerExceptions = 0;

/// 服务列表
/// 当前只有一个namespace HCC适用，所以返回的是HCC的service列表
ClassMethod getServices() As %Stream.Object
{
   Return ..getOneNamespaceServices("HCC")
}

/// 包括总数，成功数（返回AA的数字），失败（返回AE），错误（内部错误，BS向web application返回500）。统计的时长为。。。<br/>
/// The method arguments hold values for:<br/>
///     action, action<br/>
ClassMethod getHCCServiceStatistic(action As %String) As %Stream.Object
{
    //(Place business logic here)
    //Do ..%SetStatusCode(<HTTP_status_code>)
    //Do ..%SetHeader(<name>,<value>)
    //Quit (Place response here) ; response may be a string, stream or dynamic object
}

/// 关于什么是服务暂时定义为：1. running production里的BS,2. REST服务，没在produciton中的SOAP暂时不考虑。输出为service名字，类型(BS或者REST),如果是REST打印url<br/>
/// The method arguments hold values for:<br/>
///     namespace<br/>
ClassMethod getOneNamespaceServices(namespace As %String) As %Stream.Object
{
    Set currentNS=$NAMESPACE
    Set queryNS=$ZCONVERT(namespace,"U")
   	Set formatter = ##class(%JSON.Formatter).%New()
    Set code ="", message=""
    Set pResponse=[], errorResponse={}
    
    ZNspace queryNS
   
   	//process SQL
   	Set sqlstring="call Ens_Util.Statistics_EnumerateHostStatus()"
   	Set tStatement = ##class(%SQL.Statement).%New()
 	
 	Set qStatus = tStatement.%Prepare(sqlstring)
   	If qStatus'=1 {
	   Set errorResponse.code=500
	   	Set errorResponse.message = $SYSTEM.Status.GetErrorText(qStatus)
		Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
        Quit formattedResponse
	}
  	Set resultSet = tStatement.%Execute()
  	
    // Process SQL resultSet
	If (resultSet.%SQLCODE = 0) 
    {   
	    While (resultSet.%Next() '= 0) 
    	{   
            If resultSet.%Get("Type")="BusinessService"
            {   Set record = {}   //why not out?
                Set record.hostname=resultSet.%Get("Name")
                Set record.type=resultSet.%Get("Type")
                Set record.status=resultSet.%Get("Status")
                //do dynamicObject.%Set(resultSet.%Get("Name"),resultSet.%Get("Type"))
           	    Set recResults=pResponse.%Push(record)  
            }        
    	}   	
    }
    Else 
    { 	Set pResponse = {"code":500,"message":"sorry"}
    } 
  	Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	ZNspace currentNS
    Quit formattedResponse
}

/// 获取单一命名空间正在运行的production的业务组件信息<br/>
/// The method arguments hold values for:<br/>
///     namespace<br/>
ClassMethod getBusinessHostInfo(namespace As %String) As %Stream.Object
{
     Set currentNS=$NAMESPACE
    Set queryNS=$ZCONVERT(namespace,"U")
   	Set formatter = ##class(%JSON.Formatter).%New()
    Set code ="", message=""
    Set pResponse=[], errorResponse={}
    
    ZNspace queryNS
   
   	//process SQL
   	Set sqlstring="call Ens_Util.Statistics_EnumerateHostStatus()"
   	Set tStatement = ##class(%SQL.Statement).%New()
 	
 	Set qStatus = tStatement.%Prepare(sqlstring)
   	If qStatus'=1 {
	   Set errorResponse.code=500
	   	Set errorResponse.message = $SYSTEM.Status.GetErrorText(qStatus)
		Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
        Quit formattedResponse
	}
  	Set resultSet = tStatement.%Execute()
  	
    // Process SQL resultSet
	If (resultSet.%SQLCODE = 0) 
    {   
	    While (resultSet.%Next() '= 0) 
    	{   Set record = {}   //why not out?
            Set record.hostname=resultSet.%Get("Name")
            Set record.type=resultSet.%Get("Type")
            Set record.status=resultSet.%Get("Status")
            //do dynamicObject.%Set(resultSet.%Get("Name"),resultSet.%Get("Type"))
           	Set recResults=pResponse.%Push(record)          
    	} 
    	
    	//get production status 
    	//------start------ update on 2022-06-22 by JW
    	Set tSC=##class(Ens.Director).GetProductionStatus(.tProductionName,.tState)
		Quit:$$$ISERR(tSC)
 		If tState'=$$$eProductionStateRunning {
   			Set record = {}   //why not out?
            //set record.hostname= tProductionName
            Set record.type= "Production"
            Set record.status= $CASE(tState,2:"Stopped",3:"Suspended",4:"Troubled",5:"Network Stopped")
            //do dynamicObject.%Set(resultSet.%Get("Name"),resultSet.%Get("Type"))
           	Set recResults=pResponse.%Push(record) 
   		}  	
   		//------end------
    }
    Else 
    { 	Set pResponse = {"code":500,"message":"sorry"}
    } 
  	Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)

    //get rest app
    Set sc=##class(%REST.API).GetRESTApps(namespace,.appList)
    If $$$ISOK(sc) Set sc=##class(%REST.API).ListToArray(appList,.response)
    
   
    
   	ZNspace currentNS
    Quit formattedResponse
}

/// 统计当天（从零点到当前时间）各个组件的消息计数，或者当给定时间间隔，统计时间间隔内的消息计算<br/>
/// The method arguments hold values for:<br/>
///     namespace<br/>
///     beginTime, begin time<br/>
///     endTime, end time<br/>
ClassMethod getActivityData(namespace As %String, beginTime As %String, endTime As %String) As %Stream.Object
{
    Set currentNS=$NAMESPACE, queryNS=$ZCONVERT(namespace,"U")
   	ZNspace queryNS
   	Set formatter = ##class(%JSON.Formatter).%New()
   	Set tStatement = ##class(%SQL.Statement).%New()
    Set pResponse=[], errorResponse={}
    
    //ROUND(SUM(totalduration)/SUM(totalcount),4 )，其中4代表返回的位数
    //AvgDuration返回的时间单位是秒
   	Set SQLPrefix = "SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot = ( SELECT Date(NOW())) and  HostName not LIKE 'ENS.%' group by HostName"

    //仅处理没有参数的查询
    If ('$DATA(beginTime) & '$DATA(endTime)) 
    {   Set sqlstring="SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot = ( SELECT Date(NOW())) and  HostName not LIKE 'ENS.%' group by HostName"
   		Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute()
    }ElseIf ($DATA(beginTime) & $DATA(endTime))
    //处理有开始时间段和截止时间段参数的查询
    {
        Set sqlstring="SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot between ? and  ? and  HostName not LIKE 'ENS.%' group by HostName"  	
	   	Set tStatement.%SelectMode=1
	   	Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute(beginTime,endTime)

    }ElseIf ($DATA(beginTime) & '$DATA(endTime))
    //处理仅有开始时间段的查询
    {   Set sqlstring="SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot >=? and  HostName not LIKE 'ENS.%' group by HostName"  	
	   	Set tStatement.%SelectMode=1
	   	Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute(beginTime)
    }ElseIf ($DATA(endTime) & '$DATA(beginTime))
    //处理仅有截止时间段的查询
   	{	Set sqlstring="SELECT hostname, sum(totalcount)  as TotalCount, sum(totalduration)/sum(totalcount) as AvgDuration FROM Ens_Activity_Data.hours where timeslot <=? and  HostName not LIKE 'ENS.%' group by hostname"	
	   	Set tStatement.%SelectMode=1
	   	Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute(endTime)
   	}

   	#; //process time period
   	#; if ('$DATA(beginTime))
   	#; {	SET sqlstring="SELECT hostname, totalcount, totalduration/totalcount as AvgDuration, sitedimension FROM  Ens_Activity_Data.Days where timeslot=(select max(timeslot) FROM Ens_Activity_Data.Days)"
   	#; 	SET qStatus = tStatement.%Prepare(sqlstring)
   	#; 	set resultSet = tStatement.%Execute()
   	#; }else
   	#; { 
	#; 	SET sqlstring="SELECT hostname, totalcount, totalduration/totalcount as AvgDuration, sitedimension FROM Ens_Activity_Data.hours where timeslot>? and timeslot<? group by hostname"  	
	#;    	SET qStatus = tStatement.%Prepare(sqlstring)
   	#; 	set resultSet = tStatement.%Execute(beginTime,endTime)
	#; }
   
   	If qStatus'=1 {
	    Set pResponse={"code":500,"message":"prepare failed"}	
	    Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	    Write formattedResponse.Read()
        Quit formattedResponse
	}
  	
	If (resultSet.%SQLCODE = 0) 
    {
	    While (resultSet.%Next() '= 0) {
           	Set record = {}
           	//set HostNameInCN = ..NameLookUp($ZCONVERT(resultSet.%Get("HostName"),"t"))
            Set record.hostname=resultSet.%Get("HostName")
           	Set record.totalcount=resultSet.%Get("TotalCount")
            Set record.AvgDuration=resultSet.%Get("AvgDuration")
            //set record.SiteDimension=resultSet.%Get("SiteDimension")
           	Set recResults=pResponse.%Push(record)       
    	}
    }
    Else { 	
        Set pResponse = {"code":500,"message":"sorry"}
    }
 	 
  	Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	ZNspace currentNS
    Quit formattedResponse
}

/// 将Production组件的英文名字对照成中文
ClassMethod NameLookUp(hostName As %String) As %String
{
	Set tSC=$$$OK, SQLCODE=0
	
	&SQL(
	SELECT DataValue INTO :hostNameCN FROM Ens_Util.LookupTable WHERE TableName= 'HCC.SVR.Prod.LT.HostNameLU' and KeyName=:hostName
 	)
 		If SQLCODE<0 {Write "SQLCODE error ",SQLCODE," ",%msg  Quit}
     	ElseIf SQLCODE=100 {Write "Query returns no results"  Quit}
	
	Quit hostNameCN
}

/// 通过level参数返回所有的entry或者只返回warning以上级别的记录<br/>
/// The method arguments hold values for:<br/>
///     namespace<br/>
///     level<br/>
///     beginTime, begin time<br/>
///     endTime, end time<br/>
ClassMethod getEventLog(namespace As %String, level As %String, beginTime As %String, endTime As %String) As %Stream.Object
{
    Set currentNS=$NAMESPACE
   	Set queryNS=$ZCONVERT(namespace,"U")
    Set formatter = ##class(%JSON.Formatter).%New()
    Set code ="", message=""
    Set pResponse=[], errorResponse={}
    
    //Verify level = all or nothing
    //if ($DATA(level))
	//{   set all=1
    #;     set pResponse=##class(%Stream.GlobalCharacter).%New()
	#; 	do pResponse.Write("hello,world")
	#; 	quit pResponse
	#; }

   	ZNspace queryNS
   	
    //process SQL   
   	Set sqlstring="SELECT timelogged,configname,text FROM Ens_Util.Log order by timelogged desc"
   	Set tStatement = ##class(%SQL.Statement).%New()
 	Set qStatus = tStatement.%Prepare(sqlstring)
   	If qStatus'=1 {
	    Set errorResponse.code=500
	   	Set errorResponse.message = $SYSTEM.Status.GetErrorText(qStatus)
		Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
        Quit formattedResponse
	   	}
  	Set resultSet = tStatement.%Execute()
  	
    // Process SQL resultSet
	If (resultSet.%SQLCODE = 0) 
    {   If ($DATA(pageNumber)&& $DATA(pageSize))
        {
            Set startpoint= (pageNumber-1)*pageSize+1
            Set count=1
            While (resultSet.%Next() '= 0){
            If ((count >=startpoint) && (count<(startpoint+pageSize))){ Write "count:"_count,!
                Set record=pResponse.%Push(resultSet.timelogged_","_resultSet.configname_","_resultSet.text,"string")
            }
            Set count = count + 1
            }     

        }
        Else{
    	    While (resultSet.%Next() '= 0){
            Set record=pResponse.%Push(resultSet.timelogged_","_resultSet.configname_","_resultSet.text,"string")
            } 
        }    
    }
    Else 
    { 	Set pResponse = {"code":500,"message":"sorry"}
    }  
  	Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   Write formattedResponse.Read()
   	ZNspace currentNS
    Quit formattedResponse
}

/// 统计当天（从零点到当前时间）业务服务组件的消息计数，或者当给定时间间隔，统计时间间隔内的消息计算<br/>
/// The method arguments hold values for:<br/>
///     namespace<br/>
///     action, action<br/>
///     beginTime, begin time<br/>
///     endTime, end time<br/>
///     top, top Number<br/>
ClassMethod getActivityDataBS(namespace As %String, action As %String, beginTime As %String, endTime As %String, top As %Integer) As %Stream.Object
{
    //(Place business logic here)
    //Do ..%SetStatusCode(<HTTP_status_code>)
    //Do ..%SetHeader(<name>,<value>)
    //Quit (Place response here) ; response may be a string, stream or dynamic object
    
    Set currentNS=$NAMESPACE, queryNS=$ZCONVERT(namespace,"U")
   	ZNspace queryNS
   	Set formatter = ##class(%JSON.Formatter).%New()
   	Set tStatement = ##class(%SQL.Statement).%New()
    Set pResponse=[], errorResponse={}
   	Set SQLPrefix = "SELECT hostname, SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 )*1000   as AvgDuration FROM  Ens_Activity_Data.Days where timeslot =  ( SELECT Date(NOW()))and HostType=1 and HostName not LIKE 'ENS.%' group by hostname"
	
   
    
     //仅处理没有参数的查询
    If ('$DATA(beginTime) & '$DATA(endTime)) 
    {   Set sqlstring="SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot = ( SELECT Date(NOW())) and  HostName not LIKE 'ENS.%' and HostType=1 group by HostName"
   		Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute()
    }ElseIf ($DATA(beginTime) & $DATA(endTime))
    //处理有开始时间段和截止时间段参数的查询
    {
        Set sqlstring="SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot between ? and  ? and  HostName not LIKE 'ENS.%' and HostType=1 group by HostName"  	
	   	Set tStatement.%SelectMode=1
	   	Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute(beginTime,endTime)

    }ElseIf ($DATA(beginTime) & '$DATA(endTime))
    //处理仅有开始时间段的查询
    {   Set sqlstring="SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot >=? and  HostName not LIKE 'ENS.%' and HostType=1 group by HostName"  	
	   	Set tStatement.%SelectMode=1
	   	Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute(beginTime)
    }ElseIf ($DATA(endTime) & '$DATA(beginTime))
    //处理仅有截止时间段的查询
   	{	Set sqlstring="SELECT hostname, sum(totalcount)  as TotalCount, sum(totalduration)/sum(totalcount) as AvgDuration FROM Ens_Activity_Data.hours where timeslot <=? and  HostName not LIKE 'ENS.%' and HostType=1 group by hostname"	
	   	Set tStatement.%SelectMode=1
	   	Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute(endTime)
   	}

   	#; //process time period
   	#; if ('$DATA(beginTime))
   	#; {	SET sqlstring="SELECT hostname, totalcount, totalduration/totalcount as AvgDuration, sitedimension FROM  Ens_Activity_Data.Days where timeslot=(select max(timeslot) FROM Ens_Activity_Data.Days) and HostType =1"
   	#; 	SET qStatus = tStatement.%Prepare(sqlstring)
   	#; 	set resultSet = tStatement.%Execute()
   	#; }else
   	#; { 
	#; 	SET sqlstring="SELECT hostname, totalcount, totalduration/totalcount as AvgDuration, sitedimension FROM Ens_Activity_Data.hours where timeslot>? and timeslot<?  and HostType =1 group by hostname"  	
	#;    	SET qStatus = tStatement.%Prepare(sqlstring)
   	#; 	set resultSet = tStatement.%Execute(beginTime,endTime)
	#; }
   
   	If qStatus'=1 {
	    Set pResponse={"code":500,"message":"prepare failed"}	
	    Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	    Write formattedResponse.Read()
        Quit formattedResponse
	}
  	
	If (resultSet.%SQLCODE = 0) 
    {
	    While (resultSet.%Next() '= 0) {
           	Set record = {}
           	//set HostNameInCN = ..NameLookUp($ZCONVERT(resultSet.%Get("HostName"),"t"))
            Set record.hostname=resultSet.%Get("HostName")
           	Set record.totalcount=resultSet.%Get("TotalCount")
            Set record.AvgDuration=resultSet.%Get("AvgDuration")
            Set recResults=pResponse.%Push(record)       
    	}
    }
    Else { 	
        Set pResponse = {"code":500,"message":"sorry"}
    }
 	 
  	Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	ZNspace currentNS
    Quit formattedResponse
}

/// 统计当天（从零点到当前时间）业务操作组件的消息计数，或者当给定时间间隔，统计时间间隔内的消息计算<br/>
/// The method arguments hold values for:<br/>
///     namespace<br/>
///     action, action<br/>
///     beginTime, begin time<br/>
///     endTime, end time<br/>
///     top, top Number<br/>
ClassMethod getActivityDataBO(namespace As %String, action As %String, beginTime As %String, endTime As %String, top As %Integer) As %Stream.Object
{
    //(Place business logic here)
    //Do ..%SetStatusCode(<HTTP_status_code>)
    //Do ..%SetHeader(<name>,<value>)
    //Quit (Place response here) ; response may be a string, stream or dynamic object
    
     Set currentNS=$NAMESPACE, queryNS=$ZCONVERT(namespace,"U")
   	ZNspace queryNS
   	Set formatter = ##class(%JSON.Formatter).%New()
   	Set tStatement = ##class(%SQL.Statement).%New()
    Set pResponse=[], errorResponse={}
   	Set SQLPrefix = "SELECT hostname, SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 )*1000   as AvgDuration FROM  Ens_Activity_Data.Days where timeslot=( SELECT Date(NOW())) and HostType=3 and  HostName not LIKE 'ENS.%' group by hostname"

    //仅处理没有参数的查询
    If ('$DATA(beginTime) & '$DATA(endTime)) 
    {   Set sqlstring="SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot = ( SELECT Date(NOW())) and  HostName not LIKE 'ENS.%' and HostType=3 group by HostName"
   		Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute()
    }ElseIf ($DATA(beginTime) & $DATA(endTime))
    //处理有开始时间段和截止时间段参数的查询
    {
        Set sqlstring="SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot between ? and  ? and  HostName not LIKE 'ENS.%' and HostType=3 group by HostName"  	
	   	Set tStatement.%SelectMode=1
	   	Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute(beginTime,endTime)

    }ElseIf ($DATA(beginTime) & '$DATA(endTime))
    //处理仅有开始时间段的查询
    {   Set sqlstring="SELECT hostname,SUM(totalcount) as TotalCount, ROUND(SUM(totalduration)/SUM(totalcount),4 ) as AvgDuration  FROM  Ens_Activity_Data.Days where timeslot >=? and  HostName not LIKE 'ENS.%' and HostType=3 group by HostName"  	
	   	Set tStatement.%SelectMode=1
	   	Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute(beginTime)
    }ElseIf ($DATA(endTime) & '$DATA(beginTime))
    //处理仅有截止时间段的查询
   	{	Set sqlstring="SELECT hostname, sum(totalcount)  as TotalCount, sum(totalduration)/sum(totalcount) as AvgDuration FROM Ens_Activity_Data.hours where timeslot <=? and  HostName not LIKE 'ENS.%' and HostType=3 group by hostname"	
	   	Set tStatement.%SelectMode=1
	   	Set qStatus = tStatement.%Prepare(sqlstring)
   		Set resultSet = tStatement.%Execute(endTime)
   	}

   	#; //process time period
   	#; if ('$DATA(beginTime))
   	#; {	SET sqlstring="SELECT hostname, totalcount, totalduration/totalcount as AvgDuration, sitedimension FROM  Ens_Activity_Data.Days where timeslot=(select max(timeslot) FROM Ens_Activity_Data.Days) and HostType =3"
   	#; 	SET qStatus = tStatement.%Prepare(sqlstring)
   	#; 	set resultSet = tStatement.%Execute()
   	#; }else
   	#; { 
	#; 	SET sqlstring="SELECT hostname, totalcount, totalduration/totalcount as AvgDuration, sitedimension FROM Ens_Activity_Data.hours where timeslot>? and timeslot<?  and HostType =3 group by hostname"  	
	#;    	SET qStatus = tStatement.%Prepare(sqlstring)
   	#; 	set resultSet = tStatement.%Execute(beginTime,endTime)
	#; }
   
   	If qStatus'=1 {
	    Set pResponse={"code":500,"message":"prepare failed"}	
	    Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	    Write formattedResponse.Read()
        Quit formattedResponse
	}
  	
	If (resultSet.%SQLCODE = 0) 
    {
	    While (resultSet.%Next() '= 0) {
           	Set record = {}
           	//set HostNameInCN = ..NameLookUp($ZCONVERT(resultSet.%Get("HostName"),"t"))
            Set record.hostname=resultSet.%Get("HostName")
           	Set record.totalcount=resultSet.%Get("TotalCount")
            Set record.AvgDuration=resultSet.%Get("AvgDuration")
           	Set recResults=pResponse.%Push(record)       
    	}
    }
    Else { 	
        Set pResponse = {"code":500,"message":"sorry"}
    }
 	 
  	Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	ZNspace currentNS
    Quit formattedResponse
}

/// 最长的BS Top 5列表<br/>
/// The method arguments hold values for:<br/>
///     namespace<br/>
///     top, top Number<br/>
ClassMethod getMsgTimeSpan(namespace As %String, top As %Integer = 5) As %Stream.Object
{
    //(Place business logic here)
    //Do ..%SetStatusCode(<HTTP_status_code>)
    //Do ..%SetHeader(<name>,<value>)
    //Quit (Place response here) ; response may be a string, stream or dynamic object
    
    Set currentNS=$NAMESPACE, queryNS=$ZCONVERT(namespace,"U")
   	ZNspace queryNS
   	Set formatter = ##class(%JSON.Formatter).%New()
   	Set tStatement = ##class(%SQL.Statement).%New()
    Set pResponse=[], errorResponse={}   
   	
   	Set sqlstring="SELECT top "_top_" 5 SessionId ,SourceBusinessType ,SourceConfigName , DATEDIFF(ms,MIN(TimeCreated),MAX(TimeCreated)) AS DateTimeDiff  from ("
				_" SELECT * from Ens.MessageHeader where ID in (SELECT  MIN(ID)  FROM Ens.MessageHeader  group by SessionId )"
				_" UNION " 
				_" SELECT  * from Ens.MessageHeader  where ID in (SELECT CorrespondingMessageId from Ens.MessageHeader where ID in (SELECT  MIN(ID)  FROM Ens.MessageHeader  group by SessionId ))"
				_" ) as tmpTable group by SessionId "
	Set qStatus = tStatement.%Prepare(sqlstring)
   	Set resultSet = tStatement.%Execute()
   
   	If qStatus'=1 {
	    Set pResponse={"code":500,"message":"prepare failed"}	
	    Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	    Write formattedResponse.Read()
        Quit formattedResponse
	}
  	
	If (resultSet.%SQLCODE = 0) 
    {
	    While (resultSet.%Next() '= 0) {
           	Set record = {}
           	Set record.sessionId=resultSet.%Get("SessionId")
           	Set record.hostname=resultSet.%Get("SourceConfigName")
           	//Set record.hostname = ..NameLookUp($ZCONVERT(resultSet.%Get("SourceConfigName"),"t"))
            Set record.timespan=resultSet.%Get("DateTimeDiff")
            Set recResults=pResponse.%Push(record)       
    	}
    }
    Else { 	
        Set pResponse = {"code":500,"message":"sorry"}
    }
 	 
  	Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	ZNspace currentNS
    Quit formattedResponse
}

/// 最长的BS Top 5列表<br/>
/// The method arguments hold values for:<br/>
///     namespace<br/>
///     top, top Number<br/>
ClassMethod getmsgCount(namespace As %String, top As %Integer) As %Stream.Object
{
    //(Place business logic here)
    //Do ..%SetStatusCode(<HTTP_status_code>)
    //Do ..%SetHeader(<name>,<value>)
    //Quit (Place response here) ; response may be a string, stream or dynamic object
    
    Set currentNS=$NAMESPACE, queryNS=$ZCONVERT(namespace,"U")
   	ZNspace queryNS
   	Set formatter = ##class(%JSON.Formatter).%New()
   	Set tStatement = ##class(%SQL.Statement).%New()
    Set pResponse=[], errorResponse={}   
   	
   	Set sqlstring="SELECT COUNT(*) as MsgCnt,'出错消息数' as MsgStatus from Ens.MessageHeader where IsError =1 "
 					_" UNION "
 					_"SELECT COUNT(*) as MsgCnt ,'正确消息数' as MsgStatus from Ens.MessageHeader where IsError =0 "
	Set qStatus = tStatement.%Prepare(sqlstring)
   	Set resultSet = tStatement.%Execute()
   
   	If qStatus'=1 {
	    Set pResponse={"code":500,"message":"prepare failed"}	
	    Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	    Write formattedResponse.Read()
        Quit formattedResponse
	}
  	
	If (resultSet.%SQLCODE = 0) 
    {
	    While (resultSet.%Next() '= 0) {
           	Set record = {}
           	Set record.MsgCnt=resultSet.%Get("MsgCnt")
           	Set record.MsgStatus=resultSet.%Get("MsgStatus")
            Set recResults=pResponse.%Push(record)       
    	}
    }
    Else { 	
        Set pResponse = {"code":500,"message":"sorry"}
    }
 	 
  	Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	ZNspace currentNS
    Quit formattedResponse
}

/// HCC服务调用统计
ClassMethod getHCCServiceMatrix() As %Stream.Object
{
	Set formatter = ##class(%JSON.Formatter).%New()
   	Set tStatement = ##class(%SQL.Statement).%New()
    Set pResponse=[], errorResponse={} 
   	
   	#; SET sqlstring="select lt.KeyName As ServiceName,IFNULL(su.Invoked,0,su.Invoked) as Invoked  from Ens_Util.LookupTable lt"
	#; 			 _ " left join ("
	#; 			 _ " select  %EXACT(svr.Action) as ServiceName, count(svr.ID) As Invoked from HCC_SVR_Prod_MSG.SVRRequest svr"
	#; 			 _ " Group by svr.Action"
	#; 			 _ " ) su"
	#; 			 _ " On lt.KeyName = su.ServiceName "
	#; 			 _ " where lt.TableName = 'HCC.SVR.Prod.LT.ActionSchema'"

   	Set sqlstring=" select t.TopicName As ServiceName,IFNULL(su.Invoked,0,su.Invoked) as Invoked  from HCC_SVR_PubSub.Topic t"
				 _ " left join ("
				 _ " select  %EXACT(svr.Action) as ServiceName, count(svr.ID) As Invoked from HCC_SVR_Prod_MSG.SVRRequest svr"
				 _ " Group by svr.Action"
				 _ " ) su"
				 _ " On t.TopicName = su.ServiceName "
	
	Set qStatus = tStatement.%Prepare(sqlstring)
   	Set resultSet = tStatement.%Execute()
   
   	If qStatus'=1 {
	    Set pResponse={"code":500,"message":"prepare failed"}	
	    Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
   	    Write formattedResponse.Read()
        Quit formattedResponse
	}
  	// 还有点问题， 上面sql查到的 invoked = 0 的项目push 不出去。
	If (resultSet.%SQLCODE = 0) 
    {
	    While (resultSet.%Next() '= 0) {
			If 0<resultSet.%Get("Invoked") {
				Set record = {}
				// 原来有个中英文对照表，后来取消了
				// Set record.ServiceName = ..NameLookUp($ZCONVERT(resultSet.%Get("ServiceName"),"t"))
           		Set record.ServiceName=resultSet.%Get("ServiceName")
           		Set record.Invoked=resultSet.%Get("Invoked")
            	Set recResults=pResponse.%Push(record)  
			}	     
    	}
    }
    Else { 	
        Set pResponse = {"code":500,"message":"sorry"}
    }
 	 
  	Set tSC= formatter.FormatToStream(pResponse,.formattedResponse)
    Quit formattedResponse
}

}
